from flask import abort
from flask import current_app
from flask import g
from flask import render_template
from flask import session

from info import constants, db
from info.models import  News
from info.utils.common import user_login_data
from . import news_detail_blu
@news_detail_blu.route('/<news_id>')
@user_login_data
def news_detail(news_id):
    user = g.user
        # 新闻点击排行
    try:
        news_click = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

        # 查询详情页的这篇新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        abort(404)

        # 点击量+1
    news.clicks += 1

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)

    data = {
        "user": user if user else None,  # 如果user存在就返回user.to_dict(),如果不存在就返回None
        "news_click": news_click,
        "news": news.to_dict()
    }
    return render_template("detail.html" ,data=data)